package foo.bar.wiki.web.action.user;

import foo.bar.wiki.web.action.BaseActionBean;
import foo.bar.wiki.web.extension.UserTypeConverter;
import foo.bar.wiki.domain.User;
import foo.bar.wiki.services.UserService;
import foo.bar.wiki.services.exception.BusinessLogicExecution;
import foo.bar.wiki.security.UserAccountRealm;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.controller.LifecycleStage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class EditProfileActionBean extends BaseActionBean {

    private static final Log LOG = LogFactory.getLog(EditProfileActionBean.class);

    public static final String VIEW = "/user/editProfile.jsp";

    private UserService userService;

    @ValidateNestedProperties({
        @Validate(field="email", trim = true, required=true, on={"save"})
    })
    private User user;



    @DefaultHandler
    public Resolution view()  {
        user = userService.getUserById(getCurrentUser().getId());
        return new ForwardResolution(generateThemePath(VIEW));
    }




    public Resolution save() throws Throwable {
        return handleBusinessLogicException(new BusinessLogicExecution(){
            public Resolution execute() throws Throwable {
                if (!UserAccountRealm.ANONYMOUS_USER_ACCOUNT.getUser().equals(user)) {
                    userService.updateUser(user);
                    getContext().getMessages().add(new SimpleMessage("Profile saved"));
                    return new RedirectResolution(EditProfileActionBean.class, "view");
                }
                getContext().getValidationErrors().addGlobalError(new SimpleError("Anonmous user's profile cannot be saved"));
                return new RedirectResolution(EditProfileActionBean.class, "view");
            }
        });
    }
    @Before(stages={LifecycleStage.BindingAndValidation}, on={"save"})
    public void before_save() {
        user = userService.getUserById(getCurrentUser().getId());
    }


    @SpringBean("userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
